<template>
  <div>
    <loaction @getschool="getSchoolid"></loaction>
    <mt-loadmore :topMethod="loadTop" class="p_list" ref="loadmore">
      <ul>
        <li v-for="item in productList" :key="item.id">
          <div class="p_list_div">
            <p class="div1">
              <span>
                <img src="../../static/images/1.jpg" alt="" height="65">
              </span>
              <span>
                <p class="p_list_d_p1">{{item.hash.pname}}({{item.hash.fromat}})</p>
                <p><i class="iconfont icon-xingxing"></i>&nbsp;&nbsp;库存{{item.hash.number}}</p>
              </span>
            </p>
            <p>价格：<i style="font-size:0.2rem">￥</i><i>{{item.hash.amount}}</i>&nbsp;&nbsp;<mt-button @click="gocf(item)" type="primary" class="ordering">加入购物车</mt-button></p>
          </div>
        </li>
      </ul>
    </mt-loadmore>
    <div class="p_cart" @click="checkOrder" v-if="orderingNum">
      <span>
        <i class="iconfont icon-shangpin1"></i>
        <b style="position:fixed">{{orderingNum}}</b>
      </span>
    </div>
    <mt-popup
      v-model="popupVisible"
      popupTransition="popup-fade"
      position="bottom"
      modal="true"
      closeOnClickModal="true"
      style="width:100%"
    >
      <div class="p_c_list">
        <ul>
          <li v-for="item in choosedList" :key="item.id">
            <span>{{item.hash.pname}}{{item.hash.fromat}}({{item.hash.tastename}}<b v-if="item.hash.fixingname">,{{item.hash.fixingname}}</b>)</span>
            <span><i style="font-size:0.2rem">￥</i>{{item.hash.price}}</span>
            <div class="p_c_div">
              <i class="iconfont icon-jian" @click="adjustNumber(item,'reduce')"></i>
              <input type="text" readonly v-model="item.hash.number">
              <i class="iconfont icon-jia1" @click="adjustNumber(item,'add')"></i>
            </div>
          </li>
          <li v-if="choosedList.length==0" style="text-align:center">暂无任何商品</li>
        </ul>
        <p v-if="choosedList.length">总价格：
          <span><i style="font-size:0.2rem">￥</i><b style="font-weight:bold;font-size:0.4rem">{{totalMoney}}</b></span>
          <span @click="ordering">去结算</span>
        </p>
        <p v-else>总价格：
          <span><i style="font-size:0.2rem">￥</i>{{totalMoney}}</span>
          <span style="background:#ccc">去结算</span>
        </p>
      </div>
    </mt-popup>
    <transition name="fade">
      <choosefood v-show="isshowcf" :gocfData="this.gocfData" :changisshowcf="this.changisshowcf" :sid="this.sid"
        @getChoosedData="getChoosedData"
      ></choosefood>
    </transition>
  </div>
</template>
<script>
import choosefood from '~/components/base/choosefood.vue';
import loaction from '~/components/base/loaction.vue';

export default {

  data() {
    return {
      ts: this.newStore(),
      gocfData: {},
      choosedList: [],
      isshowcf: false,
      isChoose: null,
      popupVisible: false,
      schoolname: '',
      value: '',
      add: '',
      sid: '',
      productList: [],
      kucun: {},
      kucun1: {},
    };
  },
  components: {
    choosefood,
    loaction,
  },
  methods: {
    loadTop() {
      setTimeout(() => {
        this.getProList(this.sid);
        this.$refs.loadmore.onTopLoaded();
      }, 500);
    },
    getkucun1() {
      this.kucun1 = {};

      let sum = 0;
      for (let i = 0; i < this.choosedList.length; i += 1) {
        sum = parseInt(this.choosedList[i].hash.number, 10);
        if (this.kucun1[this.choosedList[i].hash.pname + this.choosedList[i].hash.fromat]) {
          this.kucun1[this.choosedList[i].hash.pname + this.choosedList[i].hash.fromat]
          += sum;
        } else {
          this.kucun1[this.choosedList[i].hash.pname + this.choosedList[i].hash.fromat]
          = sum;
        }
        const fixingname = this.choosedList[i].hash.fixingname;
        const dishes = fixingname.split(',');
        for (let j = 0; j < dishes.length; j += 1) {
          if (this.kucun1[dishes[j]]) {
            this.kucun1[dishes[j]] += sum;
          } else {
            this.kucun1[dishes[j]] = sum;
          }
        }
      }

      console.log(this.kucun1);
    },
    checkkucun(obj1, obj2) {
      // console.log(key1, obj1[key1]);
      // console.log(key2, obj2[key2]);
      let result = true;
      Object.keys(obj2).forEach((key) => {
        if (obj2[key] > obj1[key]) {
          result = key;
        }
      });

      return result;
    },
    getProList(data) {
      const req = {
        handle: '1E8254760FECAC00839BD73D1C4F9A6559B7AE69B5ABEA2DEBECAA290674172DBF35823F59EB452A',
        pickid: '',
        schoolname: '',
        schoolid: data,
      };
      this.spost(this.ts, '/mainservlet', req).then((ts) => {
        this.productList = ts.d.data.operation1;
        for (let i = 0; i < this.productList.length; i += 1) {
          this.kucun[this.productList[i].hash.pname + this.productList[i].hash.fromat] = parseInt(this.productList[i].hash.number, 10);
        }
        console.log(this.kucun);
      });
    },
    getSchoolid(data1, data2) {
      this.getProList(data1);
      this.getcartList(data1);
      this.getKc();
      this.sid = data1;
      this.schoolname = data2;
    },
    getcartList(data) {
      const req = {
        handle: '1E8254760FECAC00839BD73D1C4F9A6559B7AE69B5ABEA2D4BA9CD20F695BCB66E8029E0F9076880',
        schoolid: data,
      };
      this.spost(this.ts, '/mainservlet', req).then((ts) => {
        this.choosedList = ts.d.data.operation1;
        this.getkucun1();
      });
    },
    getChoosedData(data, gcartid) {
      this.choosedList = data;
      // console.log(this.choosedList);
      // console.log(gcartid);

      this.getkucun1();
      const kuncunmsg = this.checkkucun(this.kucun, this.kucun1);
      if (kuncunmsg != true) {
        // alert(`${kuncunmsg}库存不足!`);
        this.$messagebox.alert(`${kuncunmsg}库存不足!`, '提示');
        this.choosedList.forEach((element, eachnum) => {
          const key = element.hash.cartid;
          if (key == gcartid) {
            // 数量-1
            element.hash.number -= 1;
            // 发送给数据库重置数量
            const res = {
              handle: '1E8254760FECAC00839BD73D1C4F9A650604169200D5D67249459003978FE1FAD5B838C924EB653E',
              cartid: gcartid,
              number: element.hash.number,
            };
            this.spost(this.ts, '/mainservlet', res).then((ts) => {
              console.log(element.hash.number);
            });

            if (element.hash.number == 0) {
              this.choosedList.splice(eachnum, 1);
            }
          }
        });
      }
    },
    gocf(item) {
      this.gocfData = item;
      this.changisshowcf();
    },
    getKc() {
      const req = {
        handle: '1E8254760FECAC00839BD73D1C4F9A6559B7AE69B5ABEA2D63E01FD879BEA8A20C5ED9DACD34425A',
      };
      this.spost(this.ts, '/mainservlet', req).then((ts) => {
        const resdata = ts.d.data.operation1;
        for (let i = 0; i < resdata.length; i += 1) {
          this.kucun[resdata[i].hash.name] = parseInt(resdata[i].hash.number, 10);
        }
      });
    },
    changisshowcf() {
      this.isshowcf = !this.isshowcf;
    },
    ordering() {
      this.$router.push({
        name: 'pay',
        query: {
          schoolid: this.sid,
          // picked: this.pid,
          schoolname: this.schoolname,
        },
      });
    },
    checkOrder() {
      this.popupVisible = true;
    },
    adjustNumber(id, fn) {
      const item = id.hash.cartid;
      this.choosedList.forEach((element, eachnum) => {
        console.log(eachnum);
        const key = element.hash.cartid;
        if (key == item) {
          if (fn == 'add') {
            element.hash.number++;

            // this.getcartList(this.sid);
            this.getkucun1();
            const kuncunmsg = this.checkkucun(this.kucun, this.kucun1);
            if (kuncunmsg != true) {
              this.$messagebox.alert(`${kuncunmsg}库存不足!`, '提示');
              element.hash.number -= 1;
              return;
            }


            console.log(this.checkkucun(this.kucun, this.kucun1));
          } else {
            if (element.hash.number == 1) {
              this.choosedList.splice(eachnum, 1);
            }
            element.hash.number--;
            0;
          }
          const res = {
            handle: '1E8254760FECAC00839BD73D1C4F9A650604169200D5D67249459003978FE1FAD5B838C924EB653E',
            cartid: id.hash.cartid,
            number: element.hash.number,
          };
          this.spost(this.ts, '/mainservlet', res).then((ts) => {
            console.log(element.hash.number);
          });
        }
      });
    },
  },
  computed: {
    orderingNum() {
      let count = 0;
      for (let i = 0; i < this.choosedList.length; i += 1) {
        count += Number(this.choosedList[i].hash.number);
      }
      return count;
    },
    totalMoney() {
      let totalMoney = 0;
      for (let i = 0; i < this.choosedList.length; i += 1) {
        totalMoney += this.choosedList[i].hash.price * this.choosedList[i].hash.number;
      }
      return totalMoney;
    },
  },
};
</script>

<style lang="stylus" scoped>
.div1
  margin-bottom 0.2rem
  height 1.2rem
  span
    display inline-block
    float left
    &:first-child
      width 40%
    &:last-child
      width 60%
      p
        height 0.5rem
        line-height 0.5rem
.ungaibian
  background #fff
.gaibian
  background #90e7d1
.choosebox
  font-size 0.25rem
  span
    border 1px solid #ccc
    border-radius 0.1rem
    padding 0.08rem 0.3rem
    margin-right 0.2rem
.p_c_list
  p
    color #fff
    height 0.8rem
    line-height 0.8rem
    padding-left 0.2rem
    background #26a2ff
    span
      color #fff
      &:nth-child(2)
        float right
        padding 0 0.2rem
        background #ff6600
        text-align center
  ul
    padding 0.1rem
    max-height 40vh
    overflow auto
    li
      height 0.6rem
      line-height 0.6rem
      margin-bottom 0.1rem
      span
        display inline-block
        &:nth-child(1)
          width 50%
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          float left
        &:nth-child(2)
          color #f60
          width 10%
          text-align center
      .p_c_div
        width 30%
        float right
        text-align center
        i
          font-size 0.4rem
          color blue
        input
          width 30%
          height 100%
          text-align center
          padding-bottom 0.2rem
.p_cart
  position fixed
  padding 0.2rem
  bottom 2rem
  right 0.4rem
  background #f9f4f4
  border-radius 50%
  i
    font-size 0.5rem
  b
    display: block
    position: fixed
    right: 0.4rem
    background: #f60
    color: #fff
    bottom: 2.5rem
    z-index: 999
    border-radius: 50%
    width: 0.4rem
    height: 0.4rem
    line-height: 0.4rem
    text-align: center;
.mint-search
  height 100%
.mint-searchbar
  background #d9d9d95c
.mint-searchbar-inner .mintui-search
  font-size 0.4rem
.p_list
  margin-bottom 0.9rem;
  padding-top 1rem
  ul
    padding 0.1rem 0.3rem
    li
      padding-bottom 0.2rem
      border-bottom  1px solid #f1f1f1
      p
        line-height 0.7rem
        &:last-child
          margin-top 0.2rem
.p_list_div
  margin-top 0.2rem
  .p_list_d_p1
    font-weight bold
  p
    .ordering
      float right
      height 0.6rem
      line-height 0.6rem
      font-size 0.25rem
    i
      color #ff6600
      font-size 0.3rem

</style>

